const service=require("../../module/service.js");
const get_from = require("../../module/service.js").get_from;
const setWatcher = require("../../module/watch.js").setWatcher;
Page({
  data:{
    shop_id: 0,
    foods_list: [],
    menumsg: [],
    categories: [],
    all_categories: [],
    promotion: '',
    menumessage:{},
    menuindex:"a0",//索引的序号
    isleft:0,
    isgoods:0, //判断控制显示样式和满减的文字与价格
    count:0,
    //这里将写组件相关的属性
    iscpn:false,
    translist:[],    //单价:shopvalue，虚拟id:foods_id、总价:price、名字:name、数量:number
    tempdiscount:0,
    is_onShow: false
  },
  onLoad:function(){
    //初始化数据
    let shop_id = getApp().globalData.curr_shop_id;
    console.log(shop_id)
      if (shop_id)
        this.data.shop_id = shop_id;
    //获取所有的分类
    get_from("food/getAllCategories").then((res)=>{
      // this.setData({
      //   all_categories: res.data
      // });
      this.data.all_categories = res.data;
    });

    //请求food/getFoodsByShopId
    this.getFoods(this.getCategories);

    //注册监听器
    setWatcher(this);
    console.log("onLoad isgoods: ", this.data.isgoods);
  },

  onShow(){
    this.data.is_onShow = true;
    getApp().globalData.shopInfo.curr_iscpn = false;
    //将全局数据同步到本页
    let shopInfo = getApp().globalData.shopInfo;
    this.setData({
      count: shopInfo.curr_count,
      isgoods: shopInfo.curr_isgoods,
      translist: shopInfo.curr_translist,
      iscpn: shopInfo.curr_iscpn
    }, ()=>{
      this.data.is_onShow = false;
      console.log("onShow isgoods: ", this.data.isgoods);
    });
  },

  //监听数据变化
  watch: {
    count(val) {
      if (this.data.is_onShow)
        return;
      getApp().globalData.shopInfo.curr_count = val;
      console.log("update count is: ", getApp().globalData.shopInfo.curr_count);
    },
    isgoods(val) {
      // console.log("is_onShow: ", this.data.is_onShow)
      if (this.data.is_onShow)
        return;
      getApp().globalData.shopInfo.curr_isgoods = val;
      console.log("update isgoods is: ", getApp().globalData.shopInfo.curr_isgoods);
    },
    translist: {
      handler: function(val){
        if (this.data.is_onShow)
          return;
        getApp().globalData.shopInfo.curr_translist = val;
        console.log("update translist is: ", getApp().globalData.shopInfo.curr_translist);
      },
      deep: true
    },
    iscpn(val) {
      if (this.data.is_onShow)
        return;
      getApp().globalData.shopInfo.curr_iscpn = val;
      console.log("update iscpn is: ", getApp().globalData.shopInfo.curr_iscpn);
    }
  },

  getFoods(callback){
    let shop_id = this.data.shop_id;
    get_from("food/getFoodsByShopId", {shop_id: shop_id}).
      then((res)=>{
        this.data.foods_list = res.data;
        console.log("set food_list: ", this.data.foods_list);
        callback();
      },()=>{
        console.log("失败");
        wx.hideLoading();
      });
  },

  getCategories(){
    let shop_id = this.data.shop_id;
    //请求获取分类
    get_from("shop/getAllCategoriesByShopId", {shop_id: shop_id}).then((res)=>{
      this.data.categories = res.data;
      let arr=[];
      for (let i=0; i<this.data.categories.length; i++)
      {
        arr.push({'name': `${this.data.categories[i]}`, 'foods': []});
      }
      this.setData({
        menumsg: arr
      });
      console.log("set menumsg: ", this.data.menumsg);
      this.dealMenuMsg();
    },()=>{
      console.log("失败");
      wx.hideLoading();
    });
  },

  dealMenuMsg(){
    let tmp_menu = this.data.menumsg;
    let all_categories = this.data.all_categories;
    //处理得到的数据
    // for (let i=0; i<this.data.foods_list.length; i++)
    // {
    //   let tmp = this.data.foods_list[i];
    //     //将这个val存入menumsg的对应foods中
    //     for (let j=0; j<tmp.categories.length; j++)
    //     {
    //       for (let x=0; x<tmp_menu.length; x++)
    //       {
    //         if (tmp_menu[x].name == all_categories[(tmp.categories[j]-1)])
    //         {
    //           tmp_menu[x].foods.push(tmp);
    //         }
    //       }
    //     }
    // }
    let len = this.data.foods_list.length;
    for (let i=0; i<tmp_menu.length; i++){
      for (let j=0; j<len; j++) {
        let tmp = this.data.foods_list[j];
        // console.log('tmp is:', tmp);
        for (let x=0; x<tmp.categories.length; x++)
        if (tmp.categories[x] == tmp_menu[i].name)
        {
          tmp_menu[i].foods.push(tmp);
        }
      }
    }
    this.setData({
      menumsg: tmp_menu
    }, ()=>{
      console.log(tmp_menu);
      // console.log(this.data.menumsg);
    });
  },

  //跳转菜品详情
  food_detail(e){
    let translist_id = 0;
    let food_id = 0;
    console.log(e);
    if (e.detail.foodid)
    {
      translist_id = e.detail.cpn_translist_id;
      food_id = e.detail.foodid;
    }
    else
    {
      food_id = e.currentTarget.dataset.foodid;
      translist_id = -1;
    }
    console.log(food_id);
    if (!food_id)
    {
      console.log("food_id is not defined!");
      return;
    }

    //跳转
    wx.navigateTo({
      url: '/pages/fdetail/fdetail?food_id=' + food_id + '&translist_id=' + translist_id,
    });
  },

  //侧边菜单跳转
  orderJump(e){
    this.setData({
      menuindex:'a' + e.currentTarget.dataset.list,
      isleft:e.currentTarget.dataset.list
    })
  },
  increaseShop(e){
    var tempobj={};
    tempobj.name=this.data.menumsg[e.currentTarget.dataset.listfun].foods[e.currentTarget.dataset.foodsfun].name;
    tempobj.price=this.data.menumsg[e.currentTarget.dataset.listfun].foods[e.currentTarget.dataset.foodsfun].price;//商品的总价格
    tempobj.shopvalue=this.data.menumsg[e.currentTarget.dataset.listfun].foods[e.currentTarget.dataset.foodsfun].price;//商品的单价
    tempobj.food_id=this.data.menumsg[e.currentTarget.dataset.listfun].foods[e.currentTarget.dataset.foodsfun].food_id;
    tempobj.attrs=this.data.menumsg[e.currentTarget.dataset.listfun].foods[e.currentTarget.dataset.foodsfun].attrs;
    //添加商品的属性信息，如果没选的话默认选属性的第一个值
    // console.log(tempobj.attrs);
    for (let i=0; i<tempobj.attrs.length; i++)
    {
      for (let j=0; j<tempobj.attrs[i].attr_val.length; j++)
      {
        if (j == 0)
        {
          if (!tempobj.attrs[i].attr_val[j].name)
            tempobj.attrs[i].attr_val[j] = {name: tempobj.attrs[i].attr_val[j], selected: true};
        }
        else
        {
          if (!tempobj.attrs[i].attr_val[j].name)
            tempobj.attrs[i].attr_val[j] = {name: tempobj.attrs[i].attr_val[j], selected: false};
        }
      }
    }
    tempobj.number=1;
    this.seekNum(tempobj);//这里进行一步相同商品的判断
    this.setData({
      isgoods:(this.data.menumsg[e.currentTarget.dataset.listfun].foods[e.currentTarget.dataset.foodsfun].price + this.data.isgoods) //商品的价格
    });
    if(this.data.isgoods > 25 && this.data.tempdiscount===0){     //是否优惠3元
      this.setData({
        count:this.data.count + 1,  //购物车的图标
        isgoods:(this.data.isgoods - 3),//商品的价格
        tempdiscount:1,         //只享受一次优惠
        //传给组件的商品数据
        translist:this.data.translist,
        promotion: '满25立减3元(手机点餐专享)'
      })
    }else{
      this.setData({
        count:this.data.count + 1,  //购物车的图标
        //传给组件的商品数据
        translist:this.data.translist
      })
    }
  },
  handleCpn(){
    this.setData({
      iscpn:!this.data.iscpn
    })
  },
  handleDelete(){
    this.setData({
      count:0,
      isgoods:0,
      translist:[],
      iscpn:false
    });
  },
  handleReduce(event){
    this.pageReduce(event.detail.cpnreduceid)
  },
  handleAdd(event){
    this.pageAdd(event.detail.cpnaddid)
  },
  handleDefinite(){
    wx.navigateTo({
      url: '/pages/definite/definite'
    })
  },

  //一些辅助函数,判断商品重复、去掉商品和添加商品
  seekNum(obj){
    if(this.data.translist.length!==0){
      const translength=this.data.translist.length;
      for(let i=0;i<translength;++i){
        if(this.data.translist[i].food_id === obj.food_id){
          this.data.translist[i].price +=  obj.price;
          ++this.data.translist[i].number
          return
        }else{
          if(i===translength-1)
          this.data.translist.push(obj)
        }
      }
    }else {
      this.data.translist.push(obj)
    }
  },

  pageReduce(tempreduceid){
    this.data.translist[tempreduceid].number--;
    const tempvalue = this.data.translist[tempreduceid].shopvalue; //取出来要删除的商品的单价
    if (this.data.translist[tempreduceid].number === 0) {
      this.cancleArray(tempreduceid);
      this.setData({
        translist: this.data.translist,
        count: this.data.count - 1,
        isgoods: this.data.isgoods - tempvalue
      });
      if (this.data.translist.length === 0) {
        this.setData({
          iscpn: !this.data.iscpn
        });
      }
    } else {
      this.data.translist[tempreduceid].price -= this.data.translist[tempreduceid].shopvalue;
      this.setData({
        translist: this.data.translist,
        count: this.data.count - 1,
        isgoods: this.data.isgoods - tempvalue
      });
    }
  },
  pageAdd(tempaddid){
    this.data.translist[tempaddid].number++;
    this.data.translist[tempaddid].price += this.data.translist[tempaddid].shopvalue;
    this.setData({
      translist: this.data.translist,
      count: this.data.count + 1,
      isgoods: this.data.isgoods + this.data.translist[tempaddid].shopvalue
    });

  },
  cancleArray(n){
    //删除translist数组中第n项的数据
    if(n === 0){
      this.data.translist.shift();
    }else{     //删除数组中对应的元素
      this.data.translist.splice(n, 1);
    }
  }
})

